package club.fuwenhao.netty;

import club.fuwenhao.bean.BaseMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.Properties;

/**
 * @author fwh
 * @Description 客户端链接
 * @email fuwenhao594@163.com
 * @date 2021/10/27 10:33 下午
 */
@Slf4j
@Data
public class BaseNettyClient {
    /**
     * 主机地址
     */
    private String host;
    /**
     * 端口
     */
    private int port;
    /**
     * 客户端启动类
     */
    private Bootstrap bootstrap;
    /**
     * 客户端处理类
     */
    private BaseNettyClientHandler baseNettyClientHandler;
    /**
     * 客户端链接流
     */
    private SocketChannel socketChannel;
    /**
     * 事件组-采用NIO
     */
    private EventLoopGroup eventExecutors = new NioEventLoopGroup();

    public void setBaseNettyClientHandler(BaseNettyClientHandler baseNettyClientHandler) {
        this.baseNettyClientHandler = baseNettyClientHandler;
    }

    /**
     * 加载地址信息
     *
     * @param
     * @return void
     * @author fuwenhao
     * @date 2021/10/28 10:26 上午
     */
    protected void getBaseAddress() throws IOException {
        Properties props = new Properties();
        props.load(new ClassPathResource("netty.properties").getInputStream());
        String host = props.getProperty("netty.host");
        String port = props.getProperty("netty.port");
        this.host = host;
        this.port = Integer.valueOf(port);
    }


    /**
     * 公共启动方法
     *
     * @param
     * @return boolean
     * @author fwh [2021/10/27 && 10:51 下午]
     */
    public boolean start() throws InterruptedException, IOException {
        getBaseAddress();
        final ChannelFuture channelFuture = getBootstrap().connect(host, port).sync();
        if (channelFuture.isSuccess()) {
            socketChannel = (SocketChannel) channelFuture.channel();
            log.info("Netty客户端启动连接成功,本地地址为:{},远程地址为:{}", socketChannel.localAddress(), socketChannel.remoteAddress());
            return true;
        } else {
            log.error("Netty客户端启动连接失败,本地地址为:{},远程地址为:{}", socketChannel.localAddress(), socketChannel.remoteAddress());
            return false;
        }
    }

    /**
     * 公共停止方法
     *
     * @param
     * @return void
     * @author fwh [2021/10/27 && 10:53 下午]
     */
    public void stop() {
        if (null != socketChannel) {
            socketChannel.flush();
            socketChannel.close();
        } else {
            log.info("socketChannel is null");
        }
    }

    /**
     * socketChannel是否打开状态
     *
     * @param
     * @return boolean
     * @author fwh [2021/10/27 && 10:58 下午]
     */
    public boolean isOpen() {
        if (null != socketChannel && socketChannel.isOpen()) {
            return true;
        }
        return false;
    }

    /**
     * 向服务端传输消息
     *
     * @param baseMsg
     * @return void
     * @author fwh [2021/10/27 && 11:00 下午]
     */
    public void sendServer(BaseMsg baseMsg) {
        if (isOpen()) {
            socketChannel.writeAndFlush(baseMsg);
        } else {
            log.info("socketChannel is closed, can`t sendServer baseMsg");
            //todo-fwh-重启并重发
        }

    }


    /**
     * 客户端核心启动器
     *
     * @param
     * @return io.netty.bootstrap.Bootstrap
     * @author fwh [2021/10/27 && 10:44 下午]
     */
    private Bootstrap getBootstrap() {
        this.bootstrap = new Bootstrap();
        bootstrap.remoteAddress(host, port)
                .group(eventExecutors)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new IdleStateHandler(20, 10, 1))
                                .addLast(new ObjectEncoder())
                                .addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)))
                                .addLast(baseNettyClientHandler);
                    }
                });
        return bootstrap;
    }

}
